package com.jzlin.funhub.admin.service.chatai;

import cn.hutool.core.thread.ThreadUtil;
import com.jzlin.funhub.framework.core.sse.SseClient;
import com.jzlin.funhub.admin.service.chatai.support.BaseChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Mock大模型问答服务
 *
 * @author Lin
 * @since 2024/11/7
 */
@Service
@Slf4j
public class MockChatAiService {
    private final String[] contents = new String[]{"测试测试测试测试测试测试测试测试", "：\n\n```", "java","\npublic", " class                                                       111111111111111111111111111111111111111111111111111111111111111111111", "\n```", "\n结束"};
    /**
     * 流式调用
     */
    public void invokeSse(BaseChatMessage message) {
        try {
            for (String content : contents) {
                SseClient.sendMessage(message.getSseId(), transferSseContent(content));
                ThreadUtil.sleep(100);
            }
            SseClient.finishSse(message.getSseId());
        } catch (Exception e) {
            log.error("问答发生异常", e);
        } finally {
            SseClient.closeSse(message.getSseId());
        }
    }

    /**
     * 对消息内容进行传输前转换
     * @param content 消息内容
     * @return
     */
    private String transferSseContent(String content) {
        String result;
        // sse传输时开头的空格会被忽略，因此使用占位符代替，接收者手动替换为空格
        if (content.startsWith(" ")) {
            result = content.replaceFirst(" ", "{{SPACE}}");
        } else {
            result = content;
        }
        // 换行符
        return result.replace("\n", "\\\\n");
    }
}
